package org.example;

import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class Main {
    public static void main(String[] args) {
        String sqlFile = "D:/IDEAfile/project/db/file.sql"; // 替换为你的SQL文件路径

        try {
            // 连接到数据库
            String url = "jdbc:mysql://localhost:3306/db001?allowMultiQueries=true"; // 启用 allowMultiQueries允许执行多条sql语句
            String username = "root";
            String password = "qqaazz111";
            Connection connection = DriverManager.getConnection(url, username, password);
            // 创建Statement对象
            Statement statement = connection.createStatement();

            // 读取SQL文件
            BufferedReader reader = new BufferedReader(new FileReader(sqlFile));
            StringBuilder stringBuilder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
            reader.close();

            // 分割SQL语句
            String[] sqlQueries = stringBuilder.toString().split(";");

            // 执行SQL语句
            for (String sqlQuery : sqlQueries) {//增强型for循环迭代sqlQueries的每一个元素复制给sqlQuery
                statement.executeUpdate(sqlQuery);
            }

            // 关闭连接和Statement
            statement.close();
            connection.close();
            System.out.println("SQL文件执行成功！");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}



